//
//  HMUserAccountViewModel.swift
//  Weibo
//
//  Created by ZhuDong on 16/5/23.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

private let userInfoKey = "com.itheima.userInfoKey"
class HMUserAccountViewModel: NSObject {
    static let shareAccountViewModel = HMUserAccountViewModel()
    var userAccount: HMUserAccount?
    
    private override init() {
        super.init()
        self.userAccount = loadUserAccount()
    }
    //判断用户token是否有效
    func userLogin()->Bool{
        if userAccount?.expires_date?.compare(NSDate()) == .OrderedDescending {
            return true
        }
        
        userAccount = nil
        return false
    }
}



//请求Token的方法

extension HMUserAccountViewModel{
    func loadAccessToken(code: String,finish:((isSuccess: Bool)->())) -> Void {
        let parameters: [String : AnyObject] = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        NetworkTools.tools.request(.POST, URLString: urlStr, parameters: parameters) { (responseObject, error) -> (Void) in
            
            if error != nil{
                print(error)
                print("请求错误1!")
                return
            }
                //请求用户信息
//            print(responseObject)
            self.loadUserInfo(responseObject,finish: finish)
        }
        
    }
    
    
}
//请求用户信息
extension HMUserAccountViewModel{
    private func loadUserInfo(response: AnyObject?,finish:((isSuccess: Bool)->())){
        
        guard let tokenInfo = response as? [String:AnyObject] else{
            print("请求错误2")
            return
        }
        let token = tokenInfo["access_token"]!
        let uid = tokenInfo["uid"]!
        let urlStr = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token":token,"uid":uid]
//        print(parameters)
        NetworkTools.tools.request(.GET, URLString: urlStr, parameters: parameters) { (responseObject, error) -> (Void) in
            guard var userInfo = responseObject as? [String:AnyObject] else{
                print("请求错误3")
                return
            }
            for(key,value) in tokenInfo{
                userInfo[key] = value
            }
            
            self.saveUserInfo(userInfo)
            finish(isSuccess: true)
        }
        
    }
}
//保存用户信息
extension HMUserAccountViewModel{
    func saveUserInfo(dict:[String : AnyObject]){
//        print(dict)
        let user = HMUserAccount(dict: dict)
        let keys = ["access_token","uid","expires_in","expires_date","name","avatar_large"]
        let userInfo = user.dictionaryWithValuesForKeys(keys)
//        print(userInfo)
        //为了解决登陆后再次判断是否显示登录页的问题
        self.userAccount = user
        
        //保存用户信息
        let userDefault =  NSUserDefaults.standardUserDefaults()
        userDefault.setValue(userInfo, forKey: userInfoKey)
        userDefault.synchronize()
//        print(NSHomeDirectory())
    }
    //读取用户信息
    func loadUserAccount() -> HMUserAccount? {
        let userDefault =  NSUserDefaults.standardUserDefaults()
        guard let dict = userDefault.objectForKey(userInfoKey) else{
            return nil
        }
        let user = HMUserAccount(dict: dict as! [String : AnyObject])
        return user
    }
}